/**************************************************************
 *@ProjectName: blweibo
 *@FileName: MessageGroup.java
 *@Date: 2011-5-31
 *@Copyright: 2011 www.hrbanlv.com Inc. All rights reserved.
 **************************************************************/
package com.zhiweibo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.zhiweibo.models.Comment;
import com.zhiweibo.models.Message;
import com.zhiweibo.models.StaticInfo;
import com.zhiweibo.models.Topic;
import com.zhiweibo.models.UnreadNum;
import com.zhiweibo.util.Constant;
import com.zhiweibo.util.HttpUtil;
import com.zhiweibo.util.TopicUtil;

/**
 * The Class MessageGroup.
 * 
 * @author SunHaibin
 * @since Android 1.6
 * @history 2011-5-31
 */
public class MessageGroup extends HomeListBaseActivity implements OnItemClickListener {

    /** The m list. */
    private List mList = new ArrayList();

    /** The info mode. */
    private int infoMode;

    /** The adapter. */
    private BaseAdapter adapter;

    /** The m task. */
    private AsyncTask mTask;

    /** The m select. */
    private int mSelect;

    /** The mode. */
    private int mode;

    /** The m page. */
    private int mPage = 1;

    /** The m back list. */
    private List mBackList = new ArrayList();

    /** The m lv. */
    private ListView mLv;

    /** The url list. */
    private List<String> urlList = new ArrayList();

    /** The wd. */
    private WeiboDB wd;

    /**
     * Load more.
     */
    private void loadMore() {
        mPage += 1;
        reloadBegine(0);
        if (mTask != null && mTask.getStatus() == Status.RUNNING) {
            mTask.cancel(true);
        }
        mTask = new MessageTask().execute(0);
    }

    /**
     * Reload.
     */
    private void reload() {
        reloadBegine(1);
        if (mTask != null && mTask.getStatus() == Status.RUNNING) {
            mTask.cancel(true);
        }
        mLv.setSelection(0);
        mBackList.clear();
        mPage = 1;
        mTask = new MessageTask().execute(0);
        switch (infoMode) {
        case 2:
            WeiboEventService.delNo(10003);
            break;
        case 3:
            WeiboEventService.delNo(10001);
            break;
        case 4:
            WeiboEventService.delNo(10002);
            break;
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.yingnet.zhiweibo.BaseActivity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.messagelist);
        setTitleBar(0, null, null, null);
        adapter = new WeiboListAdapter();
        mLv = (ListView) findViewById(R.id.mainlst);
        mLv.setAdapter(adapter);
        mLv.setOnItemClickListener(this);
        mode = getIntent().getIntExtra("mode", 2);
        wd = WeiboDB.getInstance(this);
        handleTitleBarEvent(mode);
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        super.onResume();
        mode = getIntent().getIntExtra("mode", 2);
        handleTitleBarEvent(mode);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.yingnet.zhiweibo.HomeListBaseActivity#handleTitleBarEvent(int)
     */
    @Override
    protected void handleTitleBarEvent(int p) {
        if (mTask != null && mTask.getStatus() == Status.RUNNING) {
            mTask.cancel(true);
        }
        mBackList.clear();
        mList.clear();
        infoMode = p;
        switch (infoMode) {
        case 2:
            if (UnreadNum.atmsg > 0) {
                reload();
            } else if (StaticInfo.lstAt.size() == 0) {
                mTask = new DBTask().execute(0);
            } else {
                mList.addAll(StaticInfo.lstAt);
                mBackList.addAll(mList);
                adapter.notifyDataSetChanged();
            }
            ly.mButton1.setSelected(true);
            ly.mButton2.setSelected(false);
            ly.mButton3.setSelected(false);
            ly.mButton1.setClickable(false);
            ly.mButton2.setClickable(true);
            ly.mButton3.setClickable(true);
            break;
        case 3:
            if (UnreadNum.comment > 0) {
                reload();
            } else if (StaticInfo.lstComment.size() == 0) {
                mTask = new DBTask().execute(0);

            } else {
                mList.addAll(StaticInfo.lstComment);
                mBackList.addAll(mList);
                adapter.notifyDataSetChanged();
            }
            ly.mButton1.setSelected(false);
            ly.mButton2.setSelected(true);
            ly.mButton3.setSelected(false);
            ly.mButton1.setClickable(true);
            ly.mButton2.setClickable(false);
            ly.mButton3.setClickable(true);
            break;
        case 4:
            if (UnreadNum.message > 0) {
                reload();
            } else if (StaticInfo.lstPri.size() == 0) {
                mTask = new DBTask().execute(0);

            } else {
                mList.addAll(StaticInfo.lstPri);
                mBackList.addAll(mList);
                adapter.notifyDataSetChanged();
            }
            ly.mButton1.setSelected(false);
            ly.mButton2.setSelected(false);
            ly.mButton3.setSelected(true);
            ly.mButton1.setClickable(true);
            ly.mButton2.setClickable(true);
            ly.mButton3.setClickable(false);
            break;
        }
    }

    /**
     * Change ui.
     */
    private void changeUI() {
        switch (infoMode) {
        case 2:
            for (int i = 0; i < mList.size(); i++) {
                boolean b1 = true;
                Topic t1 = (Topic) mList.get(i);
                for (int j = 0; j < mBackList.size(); j++) {
                    Topic t2 = (Topic) mBackList.get(j);
                    if (t1.getTid().equals(t2.getTid())) {
                        b1 = false;
                        break;
                    }
                }
                if (b1) {
                    mBackList.add(t1);
                }
            }
            mList.clear();
            mList.addAll(mBackList);
            break;
        case 3:
            for (int i = 0; i < mList.size(); i++) {
                boolean b1 = true;
                Comment t1 = (Comment) mList.get(i);
                for (int j = 0; j < mBackList.size(); j++) {
                    Comment t2 = (Comment) mBackList.get(j);
                    if (t1.getCid() == t2.getCid()) {
                        b1 = false;
                        break;
                    }
                }
                if (b1) {
                    mBackList.add(t1);
                }
            }
            mList.clear();
            mList.addAll(mBackList);
            break;
        case 4:
            for (int i = 0; i < mList.size(); i++) {
                boolean b1 = true;
                Message t1 = (Message) mList.get(i);
                for (int j = 0; j < mBackList.size(); j++) {
                    Message t2 = (Message) mBackList.get(j);
                    if (t1.getId() == t2.getId()) {
                        b1 = false;
                        break;
                    }
                }
                if (b1) {
                    mBackList.add(t1);
                }
            }
            mList.clear();
            mList.addAll(mBackList);
        }

        adapter.notifyDataSetChanged();
        reloadEnd();
    }

    /**
     * The Class DBTask.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class DBTask extends AsyncTask<Object, Integer, Object> {

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected List doInBackground(Object... paramArrayOfString) {
            switch (infoMode) {
            case 2:
                mList = wd.selectAt();
                if (mList.size() == 0) {
                    mList = HttpUtil.getTopics(MessageGroup.this, Constant.MENTIONS + "?count=50&page=" + mPage);
                    WeiboEventService.delNo(10003);
                    if (mList.size() > 0) {
                        wd.deleteAllAt();
                        wd.insertAt(mList);
                    }
                }
                StaticInfo.lstAt.clear();
                StaticInfo.lstAt.addAll(mList);
                break;
            case 3:
                mList = wd.selectComment();
                if (mList.size() == 0) {
                    mList = HttpUtil.getComments(MessageGroup.this, Constant.COMMENTS_TIMELINE + "?count=50&page="
                            + mPage);
                    WeiboEventService.delNo(10001);
                    if (mList.size() > 0) {
                        wd.deleteAllComment();
                        wd.insertComment(mList);
                    }
                }
                StaticInfo.lstComment.clear();
                StaticInfo.lstComment.addAll(mList);
                break;
            case 4:
                mList = wd.selectMessage();
                if (mList.size() == 0) {
                    mList = HttpUtil.getMessages(MessageGroup.this, Constant.LIST + "?count=50&page=" + mPage);
                    WeiboEventService.delNo(10002);
                    if (mList.size() > 0) {
                        wd.deleteAllMessage();
                        wd.insertMessage(mList);
                    }
                }
                StaticInfo.lstPri.clear();
                StaticInfo.lstPri.addAll(mList);
                break;
            }
            return mList;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Object result) {
            mBackList.clear();
            mBackList.addAll(mList);
            adapter.notifyDataSetChanged();
            reloadEnd();
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onCancelled()
         */
        @Override
        protected void onCancelled() {
            reloadEnd();
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            reloadBegine(1);
        }
    }

    /**
     * The Class MessageTask.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class MessageTask extends AsyncTask<Object, Integer, Object> {

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected List doInBackground(Object... paramArrayOfString) {
            switch (infoMode) {
            case 2:
                mList = HttpUtil.getTopics(MessageGroup.this, Constant.MENTIONS + "?count=50&page=" + mPage);
                if (mPage == 1) {
                    StaticInfo.lstAt.clear();
                    StaticInfo.lstAt.addAll(mList);
                    if (mList.size() > 0) {
                        wd.deleteAllAt();
                        wd.insertAt(mList);
                    }
                }
                break;
            case 3:
                mList = HttpUtil.getComments(MessageGroup.this, Constant.COMMENTS_TIMELINE + "?count=50&page=" + mPage);
                if (mPage == 1) {
                    StaticInfo.lstComment.clear();
                    StaticInfo.lstComment.addAll(mList);
                    if (mList.size() > 0) {
                        wd.deleteAllComment();
                        wd.insertComment(mList);
                    }
                }
                break;
            case 4:
                mList = HttpUtil.getMessages(MessageGroup.this, Constant.LIST + "?count=50&page=" + mPage);
                if (mPage == 1) {
                    StaticInfo.lstPri.clear();
                    StaticInfo.lstPri.addAll(mList);
                    if (mList.size() > 0) {
                        wd.deleteAllMessage();
                        wd.insertMessage(mList);
                    }
                }
                break;
            }
            return mList;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Object result) {
            changeUI();
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onCancelled()
         */
        @Override
        protected void onCancelled() {
            reloadEnd();
        }
    }

    /**
     * The Class WeiboListAdapter.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class WeiboListAdapter extends BaseAdapter {

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getCount()
         */
        @Override
        public int getCount() {
            if (mList == null || mList.size() == 0) {
                return 1;
            } else {
                return mList.size() + 2;
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getItem(int)
         */
        @Override
        public Object getItem(int paramInt) {
            return paramInt;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getItemId(int)
         */
        @Override
        public long getItemId(int paramInt) {
            return paramInt;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getView(int, android.view.View,
         * android.view.ViewGroup)
         */
        @Override
        public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
            if (mList == null || mList.size() == 0) {
                return mReloadItem;
            } else {
                paramInt--;
                if (paramInt == -1) {
                    return mReloadItem;
                } else if (paramInt == mList.size()) {
                    return mLoadmoreItem;
                } else {
                    Object object = mList.get(paramInt);
                    switch (infoMode) {
                    case 2:
                        Topic topic;
                        if (object instanceof Topic) {
                            topic = (Topic) object;
                        } else {
                            topic = new Topic();
                        }
                        if (paramView == null || !(paramView instanceof MBlogListItemView)) {
                            return new MBlogListItemView(MessageGroup.this, topic);
                        } else {
                            try {
                                ((MBlogListItemView) paramView).update(MessageGroup.this, topic);
                                return paramView;
                            } catch (Exception e) {
                                return new MBlogListItemView(MessageGroup.this, topic);
                            }
                        }
                    case 3:

                        Comment cm;
                        if (object instanceof Comment) {
                            cm = (Comment) object;
                        } else {
                            cm = new Comment();
                        }
                        if (paramView == null || !(paramView instanceof CommentMessageListItemView)) {
                            return new CommentMessageListItemView(MessageGroup.this, cm);
                        } else {
                            try {
                                ((CommentMessageListItemView) paramView).update(MessageGroup.this, cm);
                                return paramView;
                            } catch (Exception e) {
                                return new CommentMessageListItemView(MessageGroup.this, cm);
                            }
                        }
                    case 4:
                        Message m;
                        if (object instanceof Message) {
                            m = (Message) object;
                        } else {
                            m = new Message();
                        }
                        if (paramView == null || !(paramView instanceof MessageListItemView)) {
                            return new MessageListItemView(MessageGroup.this, m);
                        } else {
                            try {
                                ((MessageListItemView) paramView).update(MessageGroup.this, m);
                                return paramView;
                            } catch (Exception e) {
                                return new MessageListItemView(MessageGroup.this, m);
                            }
                        }
                    }

                    return null;
                }
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.BaseAdapter#getViewTypeCount()
         */
        @Override
        public int getViewTypeCount() {
            if (mList == null) {
                return 1;
            } else {
                return 4;
            }
        }

        /**
         * Refresh.
         */
        public void refresh() {
            notifyDataSetChanged();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget
     * .AdapterView, android.view.View, int, long)
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (view == mReloadItem) {
            reload();
        } else if (view == mLoadmoreItem) {
            loadMore();
        } else {
            position--;
            final List localList = new ArrayList();
            switch (infoMode) {
            case 2:
                startActivity(new Intent(this, DetailWeiboActivity.class)
                        .putExtra("topic", (Topic) mList.get(position)));
                break;
            case 3:
                mSelect = position;
                Comment cm = (Comment) mList.get(mSelect);
                if (StaticInfo.mUid.equals(cm.getUser().getUid())) {
                    localList.add(getString(R.string.itemmenu_delete));
                } else if (!TextUtils.isEmpty(cm.getTopic().getTid())
                        && StaticInfo.mUid.equals(cm.getTopic().getUser().getUid())) {
                    localList.add(getString(R.string.itemmenu_delete));
                }
                localList.add(getString(R.string.itemmenu_reply_comment));
                if (!TextUtils.isEmpty(cm.getTopic().getTid())) {
                    localList.add(getString(R.string.itemmenu_ori_mblog));
                }
                localList.add(String.format(getString(R.string.view_one), cm.getUser().getUsername()));
                showMenu(localList);
                break;
            case 4:
                mSelect = position;
                urlList.clear();
                localList.add(getString(R.string.itemmenu_delete));
                localList.add(getString(R.string.itemmenu_reply_message));
                localList.add(getString(R.string.copy_message));
                Matcher localMatcher = TopicUtil.getWebPattern().matcher(((Message) mList.get(mSelect)).getText());
                while (localMatcher.find()) {
                    String group = localMatcher.group(0);
                    localList.add(group);
                    urlList.add(group);
                }
                showMenu(localList);
                break;
            }
        }

    }

    /**
     * Show menu.
     * 
     * @param localList
     *            the local list
     */
    private void showMenu(final List localList) {
        AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
        localBuilder.setTitle(R.string.item_menu_title);
        CharSequence[] arrayOfCharSequence1 = new CharSequence[0];
        CharSequence[] arrayOfCharSequence2 = (CharSequence[]) localList.toArray(arrayOfCharSequence1);
        localBuilder.setItems(arrayOfCharSequence2, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                String str = (String) localList.get(paramInt);
                doItemMenu(str);
            }
        });
        localBuilder.create().show();
    }

    /**
     * Do item menu.
     * 
     * @param paramString
     *            the param string
     */
    private void doItemMenu(String paramString) {
        switch (infoMode) {
        case 3:
            Comment cm = (Comment) mList.get(mSelect);
            if (paramString.equals(getString(R.string.itemmenu_reply_comment))) {
                Intent it = new Intent(this, EditActivity.class)
                        .putExtra("cid", ((Comment) mList.get(mSelect)).getCid())
                        .putExtra("topicId", cm.getTopic().getTid()).putExtra("mode", 5);
                if (!cm.getUser().getUid().equals(StaticInfo.mUid)) {
                    it.putExtra("content", "//@" + cm.getUser().getUsername() + ":");

                }
                startActivityForResult(it, 100);
            } else if (paramString.equals(getString(R.string.itemmenu_delete))) {
                HttpUtil.getTopic(MessageGroup.this, Constant.COMMENT_DESTROY + ((Comment) mList.get(mSelect)).getCid()
                        + ".json");
                mList.remove(mSelect);
                wd.deleteComment(((Comment) mList.get(mSelect)).getCid());
                adapter.notifyDataSetChanged();
            } else if (paramString.equals(getString(R.string.itemmenu_ori_mblog))) {
                startActivity(new Intent(this, DetailWeiboActivity.class).putExtra("topic", cm.getTopic()));
            } else if (paramString.equals(String.format(getString(R.string.view_one), cm.getUser().getUsername()))) {
                startActivity(new Intent(this, UserInfoActivity2.class).putExtra("user", cm.getUser()));
            }
            break;
        case 4:
            if (paramString.equals(getString(R.string.itemmenu_reply_message))) {
                startActivityForResult(
                        new Intent(this, EditActivity.class).putExtra("uid",
                                ((Message) mList.get(mSelect)).getFromuid()).putExtra("mode", 3), 101);
            } else if (paramString.equals(getString(R.string.itemmenu_delete))) {
                HttpUtil.getTopic(MessageGroup.this, Constant.MESSAGES_DESTROY + ((Message) mList.get(mSelect)).getId()
                        + ".json");
                mList.remove(mSelect);
                wd.deleteMessage(((Message) mList.get(mSelect)).getId());
                adapter.notifyDataSetChanged();
            } else if (paramString.equals(getString(R.string.copy_message))) {
                ClipboardManager localClipboardManager1 = (ClipboardManager) getSystemService("clipboard");
                localClipboardManager1.setText(((Message) mList.get(mSelect)).getText());
                Toast.makeText(this, R.string.copy_to_clipboard, Toast.LENGTH_SHORT).show();
            } else if (Collections.binarySearch(urlList, paramString) >= 0) {
                startActivity(new Intent("android.intent.action.VIEW").setData(Uri.parse(paramString)));
            }
            break;
        }
    }
}
